var RoleList = function () {
    let AUTHORITY = $("#authority").attr("content");
    var initTable = function () {
        // 渲染列表
        var gardenId=$("select[name='gardenId']").val();
        if (gardenId===undefined){
            gardenId=0;
        }
        var oTable = $("#table").DataTable(
            {
                "bAutoWidth": true,
                // "bProcessing" : true,
                "bFilter": true,
                // "bStateSave" : true,
                // "sPaginationType" : "full_numbers",
                "aaSorting": [[0, 'desc']],
                bSort: false,
                "oLanguage": { // 汉化
                    "sProcessing": "正在加载数据...",
                    "sLengthMenu": "显示_MENU_条",
                    "sZeroRecords": "没有您要搜索的内容",
                    "sInfo": "从_START_ 到 _END_ 条记录——总记录数为 _TOTAL_ 条",
                    "sInfoEmpty": "记录数为0",
                    "sInfoFiltered": "(全部记录数 _MAX_  条)",
                    "sInfoPostFix": "",
                    "sSearch": "搜索",
                    "sUrl": "",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": " 上一页 ",
                        "sNext": " 下一页 ",
                        "sLast": " 末页 "
                    }
                },
                "aoColumns": [
                    {
                        "mData": "roleName",
                    },
                    {
                        "mData": "roleCode",
                    },
                    {
                        "mData": "roleDesc",
                    },
                    {
                        "mData": "gardenName",
                    },
                    {
                        "mData": "createTime",
                    },
                    {
                        "mData": function (source, type, val) {
                            return source;
                        },
                        "mRender": function (value, method, row) {
                            var btn = '';
                            let
                                view = '<a class="btn green role_view" data-id="'
                                    + value.id
                                    + '"><i class="icon-eye-open"></i> 查看</a>';
                            let
                                edit = '<a class="btn purple role_edit" style="margin-left:10px;" data-id="'
                                    + value.id
                                    + '" ><i class="icon-edit"></i> 编辑</a>';
                            let
                                del = '<a class="btn black role_delete" style="margin-left:10px;" data-id="'
                                    + value.id
                                    + '"><i class="icon-trash"></i> 删除</a>';
                            if (AUTHORITY
                                    .includes("PERMISSION_ROLE_VIEW")) {
                                btn += view;
                            }
                            if (AUTHORITY
                                    .includes("PERMISSION_ROLE_EDIT")) {
                                btn += edit;
                            }
                            if (AUTHORITY
                                    .includes("PERMISSION_ROLE_DELETE")) {
                                btn += del;
                            }
                            return btn;
                        }
                    }],
                bServerSide: true,
                sAjaxSource: "/rolelist",
                fnServerData: function (source, data, fnCallBack) {
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: source,
                        data: "param=" + JSON.stringify(data)+"&gardenId="+gardenId,

                        success: function (d) {
                            if (d.retCode != "1")

                                alert(d.retMsg);
                            else {

                                fnCallBack(d.retObj);
                            }
                        },
                        failure: function (d) {

                            alert("服务器无响应");
                        },
                        // complete:clearWait()
                    });
                }
            });

        jQuery('#table_wrapper .dataTables_filter input').addClass(
            "m-wrap small"); // modify table search input
        jQuery('#table_wrapper .dataTables_length select').addClass(
            "m-wrap small"); // modify table per page dropdown
        jQuery('#table_wrapper .dataTables_length select').select2();

        $('#table_column_toggler input[type="checkbox"]').change(function () {

            var column = oTable.column($(this).attr('data-column'));

            column.visible(!column.visible());
        });

        $("select[name='gardenId']").change(function () {
            oTable.draw(true);
        });
    };
    // 表单验证
    var formValid = function () {

        var form = $('#submit_form');
        var error = $('.alert-error', form);
        var success = $('.alert-success', form);

        form.validate({
            debug: true,
            doNotHideMessage: true, // this option enables to show the
            // error/success messages on tab switch.
            errorElement: 'span', // default input error message container
            errorClass: 'validate-inline', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            // onsubmit:true,
            // onfocusout:true,
            onfocusout: function (element) {
                $(element).valid()
            },
            // onkeyup:true,
            onkeyup: function (element) {
                $(element).valid()
            },
            // onclick:true,
            rules: {
                roleName: {
                    // minlength: 5,
                    required: true,
                    remote: "/rolenamecheck"
                },
                roleCode: {
                    // minlength: 5,
                    required: true
                }
            },
            messages: {
                roleName: {
                    required: "角色名不能为空.",
                    remote: "角色名已存在，请更换！"
                },
                roleCode: {
                    required: "角色码不能为空."
                }
            },
            invalidHandler: function (event, validator) { // display error
                // alert on form
                // submit
                success.hide();
                error.show();
            },

            highlight: function (element) {
                $(element).closest('.help-inline').removeClass('ok');

                $(element).closest('.control-group').removeClass('success')
                    .addClass('error');

            },

            unhighlight: function (element) {
                // hightlight
                $(element).closest('.control-group').removeClass('error');
            },

            success: function (label) {
                label.addClass('valid ok') // mark the current input as valid
                // and display OK icon
                    .closest('.control-group').removeClass('error').addClass(
                    'success'); // set success class to the control group
            },

            submitHandler: function (form) {
                success.show();
                error.hide();
            }

        });
    };
    var event = function () {
        // 1.删除
        $("#table").on("click", "td a.role_delete", function () {
            var roleId = $(this).attr("data-id");
            layer.confirm('您确定要删除吗，删除后不可恢复？', {
                title: '删除角色',
                btn: ['是', '否'],
                btnAlign: 'c'
                // 按钮
            }, function () {
                deleteRole(roleId);
            });
        });
        // 2.编辑
        $("#table").on("click", "td a.role_edit", function () {
            var roleId = $(this).attr("data-id");
            // layer.msg("编辑ID："+roleId);

            layer.open({
                title: '编辑角色',
                btn: ['是', '否'],
                type: 2,
                skin: 'layui-layer-rim', // 加上边框
                // area: ['620px', 'auto'], //宽高
                area: ["40%", "80%"],
                scrollbar: false,
                content: "/role/" + roleId,
                yes: function (index, layerno) {
                    var body = layer.getChildFrame('body', index);
                    var $form = body.find("#edit_role_form");

                    // 获取到子页面窗口对象
                    var iframeWin = window[layerno.find('iframe')[0]['name']];
                    // 调用子页面的方法获取到zTree对象
                    var treeObj = iframeWin.getTree();
                    // 获取选中节点的ID，即授权的资源ID
                    var nodes = treeObj.getCheckedNodes(true);

                    var ids = nodes.map(function (node) {
                        return node.id;
                    });

                    var form_data = $form.serializeArray();
                    var post_data = {};

                    $.map(form_data, function (n, i) {
                        post_data[n['name']] = n['value'];
                    });
                    post_data.resIds = ids;
//					layer.alert(JSON.stringify(post_data));
                    submitForm(JSON.stringify(post_data), "PUT", "/role/" + roleId);

                }
            });

        });
        // 3.查看角色权限
        $("#table").on("click", "td a.role_view", function () {
            var roleId = $(this).attr("data-id");

            layer.open({
                title: '查看角色权限',

                type: 2,
                skin: 'layui-layer-rim', // 加上边框
                area: ["40%", "80%"],
                scrollbar: false,
                content: "/roleview/" + roleId,
            });

        });

        // 4.添加
        $("#btn_add").click(function () {
            // 页面层
            layer.open({
                title: '添加角色',
                btn: ['是', '否'],
                type: 1,
                skin: 'layui-layer-rim', // 加上边框
                // area: ['620px', 'auto'], //宽高
                area: ["40%","80%"],
                content: $('#tab1'),
                scrollbar: false,
                yes: function (index, layerno) {
                    if (!$("#submit_form").valid()) {
                        return;
                    }
                    var treeObj = $.fn.zTree
                        .getZTreeObj("treeDemo"), nodes = treeObj
                        .getCheckedNodes(true);

                    let ids = nodes.map(function (node) {
                        return node.id;
                    });

                    var unindexed_array = $("#submit_form").serializeArray();
                    var indexed_array = {};

                    $.map(unindexed_array, function (n, i) {
                        indexed_array[n['name']] = n['value'];
                    });

                    indexed_array.resIds = ids;

                    submitForm(JSON.stringify(indexed_array), "POST", "/role");

                }
            });
        });
    };

    function deleteRole(roleId) {
        $.ajax({
            type: "DELETE",
            dataType: "json",
            url: "/role/" + roleId
        }).done(function (data) {
            if (data && data.retCode == 1) {
                layer.msg(data.retMsg, {
                    icon: 1
                });
                setTimeout('$("#table").DataTable().ajax.reload();', 800);

            } else {
                var s = layer.msg("对不起，删除失败！", {
                    icon: 2
                });
                layer.close(s);
            }

        }).fail(function (d) {
            layer.msg("服务器无响应", {
                icon: 2
            });

        });
    }

    /**
     * 提交表单
     *
     * @param data
     */
    function submitForm(data, type, url) {
        $.ajax({
            type: type,
            dataType: "json",
            url: url,
            contentType: "application/json;charset=utf-8",
            data: data
        }).done(function (data) {
            if (data && data.retCode == 1) {
                var l = layer.msg(data.retMsg, {
                    icon: 1
                });
                setTimeout('layer.closeAll();$("#table").DataTable().ajax.reload();', 800)
            } else {
                layer.msg(data.retMsg, {icon: 3});
            }

        }).fail(function (d) {
            layer.msg("服务器无响应");

        });
    }

    // 树控件
    var initZtree = function () {
        var setting = {
            view: {
                showIcon: false
            },
            check: {
                enable: true
                // ,chkboxType: { "Y": "p", "Y": "s" }
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
        };
        // 添加的Tree
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/getAllTreeData"
        }).done(function (data) {
            $.fn.zTree.init($("#treeDemo"), setting, data);

        }).fail(function (d) {
            layer.msg("服务器无响应");

        });
    };
    return {
        init: function () {
            // alert(AUTHORITY.includes("PERMISSION_ROLE"));
            initTable();
            event();
            formValid();
            initZtree();
        }
    };

}();